package com.weblearning.tliasweb.aop;

import com.alibaba.fastjson.JSONObject;
import com.weblearning.tliasweb.mapper.OperateLogMapper;
import com.weblearning.tliasweb.pojo.OperateLog;
import com.weblearning.tliasweb.pojo.Result;
import com.weblearning.tliasweb.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Objects;

@Aspect
@Slf4j
@Component
public class LogAspect {
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.weblearning.tliasweb.anno.Log)")
    public Object recordLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        String jwt=request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);

        //获取操作的id
        Integer operatorUser = (Integer)claims.get("id");

        LocalDateTime operatorTime = LocalDateTime.now();

        String className = proceedingJoinPoint.getTarget().getClass().getName();

        String methodName = proceedingJoinPoint.getSignature().getName();

        Object []args=proceedingJoinPoint.getArgs();
        String methodParams= Arrays.toString(args);

        long begin=System.currentTimeMillis();

        Object result=proceedingJoinPoint.proceed();

        long end=System.currentTimeMillis();

        String returnValue = JSONObject.toJSONString(result);

        Long costTime=end-begin;

        OperateLog operateLog=new OperateLog(null,operatorUser,operatorTime,className,methodName,methodParams,returnValue,costTime);

        operateLogMapper.insert(operateLog);
        log.info("操作日志为"+operateLog);

        return result;

    }

}
